package com.ncu.cloundeoffice.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.github.pagehelper.PageInfo;
import com.ncu.cloundeoffice.pojo.*;
import com.ncu.cloundeoffice.service.*;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/employee/basic")
public class TEmployeeController {


    @Autowired
    private TEmployeeService tEmployeeService;
    @Autowired
    private TDepartmentService tDepartmentService;

    @Autowired
    private TPositionService tPositionService;

    @Autowired
    private TNationService tNationService;

    @Autowired
    private TJobLevelService tJobLevelService;

    @Autowired
    private TPoliticsStatusService tPoliticsStatusService;

    /**
     * 查询所有的人员
     * @param currentPage
     * @param pageSize
     * @param tEmployee
     * @param beginDateScope
     * @return
     */
    @GetMapping("/")
    public PageInfo<TEmployee> getAllEmployee(@RequestParam(value = "currentPage",defaultValue = "1") int currentPage,
                                              @RequestParam(value = "pageSize",defaultValue = "10") int pageSize,
                                              TEmployee tEmployee,
                                              Date[] beginDateScope){
        return tEmployeeService.getAllEmployee(currentPage,pageSize,tEmployee,beginDateScope);

    }

    /**
     * 添加员工
     * @param tEmployee
     * @return
     */
    @PostMapping("/")
    public ResponseResult addEmployee(@RequestBody TEmployee tEmployee){
       return tEmployeeService.addEmployee(tEmployee);
    }

    /**
     * 查询所有的民族
     * @return
     */
    @GetMapping("/tNations")
    public List<TNation> getAllTNations(){
        return tNationService.getAllTNation();
    }

    /**
     * 查询所有的部门
     * @return
     */
    @GetMapping("/tDepartments")
    public List<TDepartment> getAllTDepartments(){
        return tDepartmentService.getAllTDepartments();
    }

    /**
     * 查询所有的政治面貌
     * @return
     */
    @GetMapping("/tPoliticsStatus")
    public List<TPoliticsStatus> getAllTPoliticsStatus(){
        return tPoliticsStatusService.getAllTPoliticsStatus();
    }

    /**
     * 查询所有的职称
     * @return
     */
    @GetMapping("/tJobLevels")
    public List<TJobLevel> getAllTJobLevels(){
        return tJobLevelService.getAllTJobLevel();
    }

    /**
     * 获取所有职位
     * @return
     */
    @GetMapping("/tPositions")
    public List<TPosition> getAllTPosition(){
        return tPositionService.getAllTPosition();
    }

    /**
     * 获取工号
     * @return
     */
    @GetMapping("/workId")
    public ResponseResult getMaxWorkId(){
        return tEmployeeService.getMaxWorkId();
    }


    /**
     * 更新员工
     * @param tEmployee
     * @return
     */
    @PutMapping("/")
    public ResponseResult updateEmployee(@RequestBody TEmployee tEmployee){
        return tEmployeeService.updateEmployee(tEmployee);
    }

    /**
     * 删除员工
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseResult deleteEmployee(@PathVariable("id") int id){
        return tEmployeeService.deleteEmployee(id);
    }


    /**
     * 导出excel员工表格
     * @param response
     */
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){

        List<TEmployee> tEmployees = tEmployeeService.getEmployeeById(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TEmployee.class, tEmployees);
        ServletOutputStream out = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入员工文件
     * @param file
     */
    @PostMapping("/import")
    public ResponseResult importEmployee(MultipartFile file){
        ImportParams importParams = new ImportParams();
        //去掉标题
        importParams.setTitleRows(1);
        List<TNation> allTNation = tNationService.getAllTNation();
        List<TPoliticsStatus> allTPoliticsStatus = tPoliticsStatusService.getAllTPoliticsStatus();
        List<TDepartment> allTDepartment = tDepartmentService.getAllTDepartment();
        List<TJobLevel> allTJobLevel = tJobLevelService.getAllTJobLevel();
        List<TPosition> allTPosition = tPositionService.getAllTPosition();
        try {
            List<TEmployee> list = ExcelImportUtil.importExcel(file.getInputStream(), TEmployee.class, importParams);
            list.forEach(tEmployee -> {
                //民族id
                tEmployee.setNationId(allTNation.get(allTNation.indexOf(new TNation(tEmployee.getTNation().getName()))).getId());
                //政治面貌id
                tEmployee.setPoliticId(allTPoliticsStatus.get(getAllTPoliticsStatus().
                        indexOf(new TPoliticsStatus(tEmployee.getTPoliticsStatus().getName()))).getId());
                //部门
                tEmployee.setDepartmentId(allTDepartment.get(allTDepartment.
                        indexOf(new TDepartment(tEmployee.getTDepartment().getName()))).getId());
                //职称
                tEmployee.setJobLevelId(allTJobLevel.get(allTJobLevel.
                        indexOf(new TJobLevel(tEmployee.getTJobLevel().getName()))).getId());
                //职位
                tEmployee.setPosId(allTPosition.get(allTPosition.
                        indexOf(new TPosition(tEmployee.getTPosition().getName()))).getId());
                tEmployee.setSalaryId(1);
            });
            int count = tEmployeeService.insertTEmployee(list);
            if(count == list.size()){
                return ResponseResult.success("导入成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.error("导入失败");
    }


}
